﻿using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using Dapper;
using Zzt.ExpertsCore.Domain.Entities;

namespace Zzt.ExpertsCore.Domain.Repository.Impl
{
    public class DapperRepositoryBase<TEntity> : IRepository<TEntity> where TEntity : BaseEntity
    {
        private readonly IUnitOfWork _unitOfWork;

        public DapperRepositoryBase(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        private IDbConnection Connection => _unitOfWork.Transaction.Connection;
        private string TableName => _unitOfWork.BuildTableName<TEntity>();


        #region Methods

        public virtual Task<IEnumerable<TEntity>> Query(string cmd, object[] parameters = null)
        {
            return _unitOfWork.QueryModel<TEntity>(cmd, parameters);
        }

        public virtual Task<TEntity> GetById(int id)
        {
            var cmd = $"SELECT * FROM {TableName} WHERE ID = :id";
            return _unitOfWork.QueryModelFirstOrDefault<TEntity>(cmd, new object[]{new{id}});
        }

        public virtual Task<int> Insert(TEntity entity)
        {
            var cmd = string.Empty;
            return Connection.ExecuteAsync(cmd);
        }

        public virtual Task<int> InsertBatches(IEnumerable<TEntity> entities)
        {
            var cmd = string.Empty;
            return Connection.ExecuteAsync(cmd);
        }

        public virtual Task<int> Update(TEntity entity)
        {
            var cmd = string.Empty;
            return Connection.ExecuteAsync(cmd);
        }

        public virtual Task<int> UpdateBatches(IEnumerable<TEntity> entities)
        {
            var cmd = string.Empty;
            return Connection.ExecuteAsync(cmd);
        }

        public virtual Task<int> Delete(TEntity entity)
        {
            var cmd = string.Empty;
            return Connection.ExecuteAsync(cmd);
        }

        public virtual Task<int> DeleteBatches(IEnumerable<TEntity> entities)
        {
            var cmd = string.Empty;
            return Connection.ExecuteAsync(cmd);
        }

        #endregion
    }
}
